use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use anyhow::{anyhow, Result};

/// 服务生命周期枚举
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ServiceLifetime {
    /// 单例：整个应用生命周期内只有一个实例
    Singleton,
    /// 瞬态：每次请求都创建新实例
    Transient,
}

/// 服务工厂函数类型
pub type ServiceFactory<T> = Box<dyn Fn(&ServiceContainer) -> Result<T> + Send + Sync>;

/// 依赖注入服务容器
///
/// 这个容器不使用trait，而是直接使用具体类型来管理服务的注册和解析。
/// 支持多线程安全访问，使用Arc和RwLock来管理服务实例的生命周期。
///
/// ## 零动态分发设计
/// - 不使用 `Arc<dyn Trait>` 或任何 trait 对象
/// - 所有服务都是具体类型 `Arc<T>`，其中 T 是具体的结构体
/// - 使用 TypeId 进行类型识别，在编译时确定类型
/// - 工厂函数返回具体类型，避免类型擦除
pub struct ServiceContainer {
    /// 存储服务工厂函数，按类型ID索引
    factories: RwLock<HashMap<TypeId, Box<dyn Any + Send + Sync>>>,
    /// 存储单例实例，按类型ID索引
    singletons: RwLock<HashMap<TypeId, Arc<dyn Any + Send + Sync>>>,
    /// 存储服务生命周期配置，按类型ID索引
    lifetimes: RwLock<HashMap<TypeId, ServiceLifetime>>,
}

impl ServiceContainer {
    /// 创建新的服务容器实例
    pub fn new() -> Self {
        Self {
            factories: RwLock::new(HashMap::new()),
            singletons: RwLock::new(HashMap::new()),
            lifetimes: RwLock::new(HashMap::new()),
        }
    }

    /// 注册单例服务
    /// 
    /// # 参数
    /// * `factory` - 创建服务实例的工厂函数
    /// 
    /// # 返回值
    /// * `Result<()>` - 注册成功返回Ok(())，失败返回错误
    pub fn register_singleton<T, F>(&self, factory: F) -> Result<()>
    where
        T: 'static + Send + Sync,
        F: Fn(&ServiceContainer) -> Result<T> + 'static + Send + Sync,
    {
        let type_id = TypeId::of::<T>();
        
        // 存储工厂函数
        {
            let mut factories = self.factories.write()
                .map_err(|_| anyhow!("Failed to acquire write lock on factories"))?;
            factories.insert(type_id, Box::new(factory));
        }
        
        // 存储生命周期配置
        {
            let mut lifetimes = self.lifetimes.write()
                .map_err(|_| anyhow!("Failed to acquire write lock on lifetimes"))?;
            lifetimes.insert(type_id, ServiceLifetime::Singleton);
        }
        
        Ok(())
    }

    /// 注册瞬态服务
    /// 
    /// # 参数
    /// * `factory` - 创建服务实例的工厂函数
    /// 
    /// # 返回值
    /// * `Result<()>` - 注册成功返回Ok(())，失败返回错误
    pub fn register_transient<T, F>(&self, factory: F) -> Result<()>
    where
        T: 'static + Send + Sync,
        F: Fn(&ServiceContainer) -> Result<T> + 'static + Send + Sync,
    {
        let type_id = TypeId::of::<T>();
        
        // 存储工厂函数
        {
            let mut factories = self.factories.write()
                .map_err(|_| anyhow!("Failed to acquire write lock on factories"))?;
            factories.insert(type_id, Box::new(factory));
        }
        
        // 存储生命周期配置
        {
            let mut lifetimes = self.lifetimes.write()
                .map_err(|_| anyhow!("Failed to acquire write lock on lifetimes"))?;
            lifetimes.insert(type_id, ServiceLifetime::Transient);
        }
        
        Ok(())
    }

    /// 解析服务实例
    /// 
    /// # 返回值
    /// * `Result<Arc<T>>` - 成功返回服务实例的Arc包装，失败返回错误
    pub fn resolve<T>(&self) -> Result<Arc<T>>
    where
        T: 'static + Send + Sync,
    {
        let type_id = TypeId::of::<T>();
        
        // 获取生命周期配置
        let lifetime = {
            let lifetimes = self.lifetimes.read()
                .map_err(|_| anyhow!("Failed to acquire read lock on lifetimes"))?;
            lifetimes.get(&type_id)
                .copied()
                .ok_or_else(|| anyhow!("Service not registered: {}", std::any::type_name::<T>()))?
        };
        
        match lifetime {
            ServiceLifetime::Singleton => self.resolve_singleton::<T>(),
            ServiceLifetime::Transient => self.resolve_transient::<T>(),
        }
    }

    /// 解析单例服务实例
    fn resolve_singleton<T>(&self) -> Result<Arc<T>>
    where
        T: 'static + Send + Sync,
    {
        let type_id = TypeId::of::<T>();
        
        // 首先检查是否已经有缓存的单例实例
        {
            let singletons = self.singletons.read()
                .map_err(|_| anyhow!("Failed to acquire read lock on singletons"))?;
            if let Some(instance) = singletons.get(&type_id) {
                return instance
                    .clone()
                    .downcast::<T>()
                    .map_err(|_| anyhow!("Failed to downcast singleton instance"));
            }
        }
        
        // 如果没有缓存实例，创建新实例
        let instance = self.create_instance::<T>()?;
        let arc_instance = Arc::new(instance);
        
        // 缓存单例实例
        {
            let mut singletons = self.singletons.write()
                .map_err(|_| anyhow!("Failed to acquire write lock on singletons"))?;
            singletons.insert(type_id, arc_instance.clone() as Arc<dyn Any + Send + Sync>);
        }
        
        Ok(arc_instance)
    }

    /// 解析瞬态服务实例
    fn resolve_transient<T>(&self) -> Result<Arc<T>>
    where
        T: 'static + Send + Sync,
    {
        let instance = self.create_instance::<T>()?;
        Ok(Arc::new(instance))
    }

    /// 创建服务实例
    fn create_instance<T>(&self) -> Result<T>
    where
        T: 'static + Send + Sync,
    {
        let type_id = TypeId::of::<T>();
        
        let factories = self.factories.read()
            .map_err(|_| anyhow!("Failed to acquire read lock on factories"))?;
        
        let factory = factories.get(&type_id)
            .ok_or_else(|| anyhow!("Factory not found for service: {}", std::any::type_name::<T>()))?;
        
        let factory = factory
            .downcast_ref::<ServiceFactory<T>>()
            .ok_or_else(|| anyhow!("Failed to downcast factory for service: {}", std::any::type_name::<T>()))?;
        
        factory(self)
    }

    /// 检查服务是否已注册
    pub fn is_registered<T>(&self) -> bool
    where
        T: 'static,
    {
        let type_id = TypeId::of::<T>();
        if let Ok(lifetimes) = self.lifetimes.read() {
            lifetimes.contains_key(&type_id)
        } else {
            false
        }
    }

    /// 获取已注册服务的数量
    pub fn service_count(&self) -> usize {
        if let Ok(lifetimes) = self.lifetimes.read() {
            lifetimes.len()
        } else {
            0
        }
    }

    /// 清除所有单例实例（主要用于测试）
    pub fn clear_singletons(&self) -> Result<()> {
        let mut singletons = self.singletons.write()
            .map_err(|_| anyhow!("Failed to acquire write lock on singletons"))?;
        singletons.clear();
        Ok(())
    }
}

impl Default for ServiceContainer {
    fn default() -> Self {
        Self::new()
    }
}

// 实现Debug trait以便调试
impl std::fmt::Debug for ServiceContainer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ServiceContainer")
            .field("service_count", &self.service_count())
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};

    #[derive(Debug)]
    struct TestService {
        id: usize,
    }

    impl TestService {
        fn new(id: usize) -> Self {
            Self { id }
        }
    }

    #[derive(Debug)]
    struct DependentService {
        test_service: Arc<TestService>,
    }

    impl DependentService {
        fn new(test_service: Arc<TestService>) -> Self {
            Self { test_service }
        }
    }

    #[tokio::test]
    async fn test_singleton_service() {
        let container = ServiceContainer::new();
        
        // 注册单例服务
        container.register_singleton::<TestService, _>(|_| {
            Ok(TestService::new(42))
        }).unwrap();
        
        // 解析两次，应该返回同一个实例
        let instance1 = container.resolve::<TestService>().unwrap();
        let instance2 = container.resolve::<TestService>().unwrap();
        
        assert_eq!(instance1.id, 42);
        assert_eq!(instance2.id, 42);
        assert!(Arc::ptr_eq(&instance1, &instance2));
    }

    #[tokio::test]
    async fn test_transient_service() {
        let container = ServiceContainer::new();
        let counter = AtomicUsize::new(0);
        
        // 注册瞬态服务
        container.register_transient::<TestService, _>(move |_| {
            let id = counter.fetch_add(1, Ordering::SeqCst);
            Ok(TestService::new(id))
        }).unwrap();
        
        // 解析两次，应该返回不同的实例
        let instance1 = container.resolve::<TestService>().unwrap();
        let instance2 = container.resolve::<TestService>().unwrap();
        
        assert_eq!(instance1.id, 0);
        assert_eq!(instance2.id, 1);
        assert!(!Arc::ptr_eq(&instance1, &instance2));
    }

    #[tokio::test]
    async fn test_dependent_service() {
        let container = ServiceContainer::new();
        
        // 注册依赖服务
        container.register_singleton::<TestService, _>(|_| {
            Ok(TestService::new(100))
        }).unwrap();
        
        // 注册依赖于其他服务的服务
        container.register_transient::<DependentService, _>(|container| {
            let test_service = container.resolve::<TestService>()?;
            Ok(DependentService::new(test_service))
        }).unwrap();
        
        // 解析依赖服务
        let dependent = container.resolve::<DependentService>().unwrap();
        assert_eq!(dependent.test_service.id, 100);
    }

    #[tokio::test]
    async fn test_service_not_registered() {
        let container = ServiceContainer::new();
        
        // 尝试解析未注册的服务
        let result = container.resolve::<TestService>();
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_is_registered() {
        let container = ServiceContainer::new();
        
        assert!(!container.is_registered::<TestService>());
        
        container.register_singleton::<TestService, _>(|_| {
            Ok(TestService::new(1))
        }).unwrap();
        
        assert!(container.is_registered::<TestService>());
    }
}
